<template>
  <div class="file-viewer-page">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button type="primary" link @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>
        返回上一页
      </el-button>
    </div>

    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="file-title">{{ fileTitle }}</h1>
      <div class="file-meta">
        <span class="file-type">文件类型: {{ fileTypeText }}</span>
        <span class="file-size">{{ fileSize }}</span>
      </div>
    </div>

    <!-- Excel 查看器 -->
    <div v-if="isExcel" class="excel-viewer-container">
      <div class="viewer-controls">
        <el-button size="small" @click="downloadFile">
          <el-icon><Download /></el-icon> 下载文件
        </el-button>
        <el-button size="small" @click="reloadExcel">
          <el-icon><Refresh /></el-icon> 重新加载
        </el-button>
      </div>

      <div class="viewer-content">
        <div v-if="loading" class="loading-overlay">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>Excel加载中...</span>
        </div>

        <div v-if="error" class="error-message">
          <el-alert type="error" :title="error" show-icon />
        </div>

        <div v-if="tableData.length && !loading" class="excel-table-container">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column
                v-for="(key, index) in tableHeaders"
                :key="index"
                :prop="key"
                :label="key"
                align="center"
                min-width="120"
            />
          </el-table>
        </div>
      </div>
    </div>

    <!-- 不支持的文件类型 -->
    <div v-else class="unsupported-type">
      <el-result
          icon="warning"
          title="不支持的文件类型"
          :sub-title="`无法预览 ${fileType} 格式的文件`"
      >
        <template #extra>
          <el-button type="primary" @click="downloadFile">
            <el-icon><Download /></el-icon> 下载文件
          </el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft, Download, Loading, Refresh } from "@element-plus/icons-vue";
import * as XLSX from "xlsx";

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const error = ref("");
const tableData = ref([]);
const tableHeaders = ref([]);

const fileType = ref("xlsx");
const fileTitle = ref("测试Excel文件");
const fileTypeText = ref("Excel表格");
const fileSize = ref("0MB");
const fileUrl = ref("/pdfjs/test.xlsx");

const isExcel = computed(() => ["xls", "xlsx", "csv"].includes(fileType.value.toLowerCase()));

// 返回
const handleBack = () => {
  router.back();
};

// 下载
const downloadFile = () => {
  const link = document.createElement("a");
  link.href = fileUrl.value;
  link.download = fileTitle.value;
  link.click();
};

// 重新加载
const reloadExcel = () => {
  loadExcelFile();
};

// 加载 Excel 数据
const loadExcelFile = async () => {
  try {
    loading.value = true;
    error.value = "";
    tableData.value = [];
    tableHeaders.value = [];

    const response = await fetch(fileUrl.value);
    if (!response.ok) throw new Error("文件加载失败");

    const arrayBuffer = await response.arrayBuffer();
    const workbook = XLSX.read(arrayBuffer, { type: "array" });

    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];

    const jsonData = XLSX.utils.sheet_to_json(worksheet, { defval: "" });
    tableData.value = jsonData;
    tableHeaders.value = jsonData.length ? Object.keys(jsonData[0]) : [];

    ElMessage.success("Excel加载成功");
  } catch (err) {
    console.error("Excel解析失败:", err);
    error.value = "Excel解析失败: " + err.message;
    ElMessage.error("Excel加载失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  const { type, title } = route.query;
  if (type) fileType.value = type;
  if (title) fileTitle.value = title;

  loadExcelFile();
});
</script>

<style scoped>
.file-viewer-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.back-button {
  margin-bottom: 20px;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
  margin-bottom: 8px;
}

.file-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.excel-viewer-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.viewer-controls {
  margin-bottom: 20px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
  display: flex;
  gap: 10px;
}

.viewer-content {
  position: relative;
  min-height: 400px;
}

.excel-table-container {
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  overflow: auto;
}

.loading-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  color: #409eff;
  z-index: 10;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 10px;
  animation: spin 1s linear infinite;
}

.error-message {
  margin: 20px 0;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.unsupported-type {
  background: white;
  padding: 40px;
  border-radius: 8px;
  text-align: center;
}

/* 响应式 */
@media (max-width: 768px) {
  .file-viewer-page {
    padding: 16px;
  }
  .viewer-controls {
    flex-direction: column;
  }
}
</style>
